package com.ruoyi.yz.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/{userID}")
public class YzWebsocketService {

    private Logger log = LoggerFactory.getLogger(getClass());

    //每个客户端都会有相应的session,服务端可以发送相关消息
    private Session session;

    //接收userID
    private Integer userID;

    //J.U.C包下线程安全的类，主要用来存放每个客户端对应的webSocket连接
    private static CopyOnWriteArraySet<YzWebsocketService> copyOnWriteArraySet = new CopyOnWriteArraySet<>();

    public Integer getUserID() {
        return userID;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userID") Integer userID) {
        this.session = session;
        this.userID = userID;
        log.info("session connect: {}", this.session.getId());
        copyOnWriteArraySet.add(this);

    }

    @OnClose
    public void onClose() {
        copyOnWriteArraySet.remove(this);
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("websocket receive msg: {}", message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("ws error: {}, sessionId={}", error.getMessage(), session.getId(), error);
    }

    public void sendMessage(String message) {
        //遍历客户端
        for (YzWebsocketService webSocket : copyOnWriteArraySet) {
            log.info("websocket broadcast: {}" + message);
            try {
                //服务器主动推送
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                log.error("ws broadcast error: {}", e.getMessage());
            }
        }
    }

}
